#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
###----------1、文件说明----------### 
''' 
* 说明：conan安装配置文件
* 时间：
* 文件：
* 作者：Smile
* 版本：0.1
* 库版本: 
 - conan: 2.14.0
* 备注： 
'''
import os,sys
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.system import package_manager
from pprint import pprint
import platform
import importlib
from datetime import datetime
import time

def getClassValue(sclass):
    '''
    获取类的子属性
    版本: 0.1
    :param sclass:
    :return:
    '''
    from types import FunctionType, BuiltinFunctionType, MethodType

    print("Get Class ", type(sclass))
    for i in dir(sclass):
        tmp = getattr(sclass, i)
        if isinstance(tmp, FunctionType) or isinstance(tmp, BuiltinFunctionType):
            print(i, "\t", type(tmp), "Function")
        else:
            print(i, "\t", type(tmp), tmp)

manager_mapping = {"Apt": ["Linux", "ubuntu", "kylin", "debian", "raspbian", "linuxmint", 'astra', 'elbrus', 'altlinux', 'pop'],
                    "Apk": ["alpine"],
                    "Yum": ["pidora", "scientific", "xenserver", "amazon", "oracle", "amzn",
                            "almalinux", "rocky"],
                    "Dnf": ["fedora", "rhel", "centos", "mageia", "nobara"],
                    "Brew": ["Darwin"],
                    "PacMan": ["arch", "manjaro", "msys2", "endeavouros"],
                    "Chocolatey": ["Windows"],
                    "Zypper": ["opensuse", "sles"],
                    "Pkg": ["freebsd"],
                    "Pkgutil": ["Solaris"]}

class SoftConfigRecipe(ConanFile):
    name = "alistinstall"
    version = "0.1"
    installversion = "v3.44.0"
    package_type = "build-scripts"

    # 个人信息
    license = "MIT"
    author = "<OSmile> <whghcyx@outlook.com>"
    url = "https://whg555.github.io"
    description = "readme description"
    topics = ("<Put some tag here>", "<here>", "<and here>")

    # 二进制配置
    settings = "os", "compiler", "build_type", "arch"

    # 针对特定系统的安装包
    packages = {
        "ubuntu" :  {
            "default" : ["gcc"], # 当前系统通用的包
            "20" : ["gcc"], # 特定版本号的包
        },
        "kylin" : {
            "default" : ["gcc"], # 当前系统通用的包
            "v10" :  ["gcc"], # 当前系统通用的包
        },
        "default" : {
            "default" : ["gcc"]
        }
    }

    def config_options(self):
        '''
        针对系统，对配置命令做一些修改
        <1>conan install .
        <1>conan create .
        <test><1>conan create .
        '''
        self.starttime = datetime.now()
        print("\033[43;34mOSmile-->", "config_options", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        print(">OS System Info")
        pprint(self.settings.values_list)
        # pprint(self.serialize())
        print("self.conf", self.conf)

        # 获取系统版本信息
        os_name = platform.system()
        self.os_name = self.os_version = self.os_base =  ""
        self.os_base = os_name
        if os_name in ["Linux", "FreeBSD"]:
            import distro
            self.os_name = distro.id() or os_name
            self.os_version = distro.version(best=True).split(".")[0]
        elif os_name == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            self.os_name = "msys2"
            self.os_version = ""
        print("System   -->", self.os_base)
        print("OSSystem -->", self.os_name)
        print("Version  -->", self.os_version)

    def configure(self):
        '''
        <2>conan install .
        <2>conan create .
        <test><2>conan create .
        '''
        print("\033[43;34mOSmile-->", "configure", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if self.os_name == "kylin":
            self.conf.define("tools.system.package_manager:tool", "apt-get")
        self.conf.define("tools.system.package_manager:mode", "install")
        self.conf.define("tools.system.package_manager:sudo", True)

    def layout(self):
        '''
        <3>conan install .
        <3>conan create .
        <test><3>conan create .
        '''
        print("\033[43;34mOSmile-->", "layout", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        # <<< 获取安装包 >>>
        arch = self.settings.arch
        if self.settings.arch == "armv8":
            arch = "arm64"
        elif self.settings.arch == "x86_64":
            arch = "amd64"

        print(self.os_base.lower())
        print(arch)
        self.filename = "alist-" + self.os_base.lower() + "-" + str(arch) + ".tar.gz"

        url = f"https://github.com/AlistGo/alist/releases/download/{self.installversion}/{self.filename}"
        print("安装文件:", self.filename)
        print("下载链接:", url)
        if not os.path.exists(self.filename):
            self.run(f"wget {url}", ignore_errors=True)

    def system_requirements(self):
        '''
        安装需要的软件
        <4>conan install .
        <4>conan create .
        <test><4>conan create .
        '''
        print("\033[43;34mOSmile-->", "system_requirements", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if self.os_base in ["Linux", "FreeBSD"]:
            self.run(f"tar -xzvf {self.filename}", ignore_errors=True)
            self.run("sudo mkdir /opt/alist", ignore_errors=True)
            self.run(f"sudo chown {os.getlogin()}:{os.getlogin()} /opt/alist", ignore_errors=True)
            self.run(f"mv alist /opt/alist/", ignore_errors=True)
            self.run(f"chmod 774 /opt/alist/alist", ignore_errors=True)
        elif self.os_base == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            os_name = "msys2"

    def generate(self):
        '''
        配置已经安装的软件
        <5>conan install .
        <5>conan create .
        '''
        print("\033[43;34mOSmile-->", "generate", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        serviceconfig = f"""[Unit]
Description=AList Service
After=network.target

[Service]
ExecStart=/opt/alist/alist server
Restart=always
User={os.getlogin()}
Group={os.getlogin()}
WorkingDirectory=/opt/alist

[Install]
WantedBy=multi-user.target
"""
        with open("/opt/alist/alist.service", "x", encoding="utf-8") as f:
            f.write(serviceconfig)
        self.run("sudo cp /opt/alist/alist.service /etc/systemd/system/alist.service")
        self.run("sudo systemctl daemon-reload")
        self.run("sudo systemctl enable alist.service")
        self.run("sudo systemctl start alist.service")
        ret = self.run("sudo systemctl status alist.service")
        try:
            f = open("/var/log/syslog")
            data = f.readlines()
            for line in data:
                if line.find("alist") != -1:
                    if line.find("admin") != -1:
                        print("网址: http://0.0.0.0:5244")
                        print("用户名: admin")
                        print("密码:", line.split(" ")[-1])
        except:
            print("error")

